package com.gee.spring.cloud.data.transform.core.dispatch;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.StrUtil;
import com.gee.spring.cloud.common.core.entity.center.config.*;
import com.gee.spring.cloud.common.starter.socket.SocketHolder;
import com.gee.spring.cloud.data.transform.core.center.config.handler.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static cn.hutool.core.text.StrPool.COMMA;
import static com.gee.spring.cloud.data.transform.core.dispatch.SocketManager.removeFilterDevice;
import static com.gee.spring.cloud.data.transform.core.dispatch.SocketManager.updateFilterDevice;

/**
 * @author gepengjun
 * @since 2024/6/19 16:11
 */
@Component
public class BaseDataDispatcher {

    private static final Logger log = LoggerFactory.getLogger(BaseDataDispatcher.class);

    private Org org;

    private OrgCenter orgCenter;

    private TransformDsl cstpHeadDsl;

    private List<Satellite> filterSateList;

    private List<Device> filterDeviceList;

    @Autowired
    private DataTransformProperties dataTransformProperties;

    @Autowired
    private SocketManager socketManager;

    @Autowired
    private OrgCenterHandler orgCenterHandler;

    @Autowired
    private OrgHandler orgHandler;

    @Autowired
    private SatelliteHandler satelliteHandler;

    @Autowired
    private DeviceHandler deviceHandler;

    @Autowired
    private TransformDslHandler transformDslHandler;

    public void init(){
        long centerIdentity = HexUtil.hexToLong(dataTransformProperties.getCenterIdentityHex8());
        orgCenter = orgCenterHandler.getByCenterIdentity(centerIdentity);
        if (orgCenter == null){
            log.error("未获取到中心,中心标识: {}", dataTransformProperties.getCenterIdentityHex8());
            return;
        }
        org = orgHandler.getById(orgCenter.getOrgId());
        if (org == null){
            log.error("未获取到组织,组织id: {}", orgCenter.getOrgId());
            return;
        }
        cstpHeadDsl = transformDslHandler.getById(orgCenter.getCstpHeadDslId());
        if (cstpHeadDsl == null){
            log.error("未获取到cstp头脚本,脚本id: {}", orgCenter.getCstpHeadDslId());
            return;
        }
        filterSateList = transFilterSateIds(orgCenter.getFilterSateIds());
        filterDeviceList = transFilterDevIds(orgCenter.getFilterDeviceIds());
        log.info("初始化中心: {}", orgCenter);
        socketManager.init(orgCenter);
    }

    public boolean filterOrg(long orgIdentity){
        return org.getOrgIdentity() != orgIdentity;
    }

    public boolean filterSatellite(long sateIdentity){
        if (CollectionUtil.isNotEmpty(filterSateList)){
            return filterSateList.stream().anyMatch(satellite -> satellite.getSateIdentity() == sateIdentity);
        }
        return false;
    }

    public boolean filterDevice(long devIdentity){
        if (CollectionUtil.isNotEmpty(filterDeviceList)){
            return filterDeviceList.stream().anyMatch(device -> device.getDevIdentity() == devIdentity);
        }
        return false;
    }

    public boolean filterSendBid(long bid){
        return socketManager.getSendFrameSet().stream().anyMatch(frame -> frame.getBid() == bid);
    }

    public boolean filterReceiveBid(long bid){
        return socketManager.getReceiveFrameSet().stream().anyMatch(frame -> frame.getBid() == bid);
    }

    public List<Device> transFilterDevIds(String devIds){
        if (StrUtil.isNotEmpty(devIds)){
            String[] split = devIds.split(COMMA);
            return Arrays.stream(split)
                    .map(Long::parseLong)
                    .map(sateId -> deviceHandler.getById(sateId))
                    .collect(Collectors.toList());
        }
        return List.of();
    }

    public List<Satellite> transFilterSateIds(String sateIds){
        if (StrUtil.isNotEmpty(sateIds)){
            String[] split = sateIds.split(COMMA);
            return Arrays.stream(split)
                    .map(Long::parseLong)
                    .map(sateId -> satelliteHandler.getById(sateId))
                    .collect(Collectors.toList());
        }
        return List.of();
    }

    public void updateOrgCenter(OrgCenter neworgCenter, OrgCenter oldOrgCenter){
        if (neworgCenter.getId().equals(orgCenter.getId())){
            //log.warn("当前中心修改, 修改后: {}", newOrgCenter);
            if (!orgCenter.getSocketDecoderId().equals(oldOrgCenter.getSocketDecoderId())){
                socketManager.getSocketConfigDtoMap().values().forEach(socketConfigDto -> SocketHolder.stopBySocketId(socketConfigDto.getId()));
                socketManager.init(orgCenter);
            }
        }
    }

    public void removeCenter(OrgCenter orgCenter) {
        if (orgCenter.getId().equals(this.orgCenter.getId())){
            log.warn("当前中心删除, 关闭连接");
            socketManager.getSocketConfigDtoMap().values().forEach(socketConfigDto -> SocketHolder.stopBySocketId(socketConfigDto.getId()));
        }
    }

    public void updateDevice(Device device) {
        updateFilterDevice(filterDeviceList, device);
        socketManager.updateDevice(device);
    }

    public void removeDevice(Device device) {
        removeFilterDevice(filterDeviceList, device);
        socketManager.removeDevice(device);
    }

    public void updateTransformDsl(TransformDsl newTransformDsl, TransformDsl oldTransformDsl){
        if (oldTransformDsl.getId().equals(cstpHeadDsl.getId())){
            cstpHeadDsl = newTransformDsl;
        }
    }

    public OrgCenter getOrgCenter() {
        return orgCenter;
    }

    public Org getOrg() {
        return org;
    }

    public TransformDsl getCstpHeadDsl() {
        return cstpHeadDsl;
    }
}
